package com.conversationboard.controller;

import java.io.IOException;
import java.sql.SQLException;
import java.util.Date;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.conversationboard.config.Configuration;
import com.conversationboard.logger.Logger;
import com.conversationboard.model.Role;
import com.conversationboard.model.SiteMessage;
import com.conversationboard.model.User;

@WebServlet(name = "AdminSiteMessageControllerServlet", urlPatterns = "/Admin/AdminSiteMessageControllerServlet")
public class AdminSiteMessageControllerServlet extends HttpServlet {

	private static final long serialVersionUID = 5322811162029366629L;


	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");

		try {

			String loginId = request.getUserPrincipal().getName();
			String text = request.getParameter("text").trim();

			User user = User.get(loginId);

			if (!SecurityChecks.passes(request, user, this)) {
				return;
			}

			if (user.getRole() != Role.SiteAdmin) {
				Logger.log(new Date(), "Not authorised to edit the site message", user);
				request.setAttribute("message", "You are not authorised to edit the site message.");
				RequestDispatcher dispatcher = request.getRequestDispatcher("/Pages/messagepage.jsp");
				dispatcher.forward(request, response);
				return;
			}

			/* All is OK, set the site message */

			SiteMessage.setMessage(text);

			response.sendRedirect(Configuration.getInstance().getRoot() + "/index.jsp");

		} catch (SQLException e) {
			throw new ServletException(e);
		}

	}

}
